ReactJS useState Hook Explained with Examples

Introduction:

In modern times, React is the most used JavaScript front-end library for making a single-page application. Hooks are mainly used in the functional components that manage the state. By using Hooks, you can use the React Lifecycle methods in functional components. Before React hooks, developers used class components for managing the state.

In this article, we will explore the ReactuseState hook with practical examples and how to manage the state.


useState in React:

This hook helps to add the state in functional components. A state is used to contain the data or properties that are used to track your application. It is a similar way to useReducer hook that is used to update the basic state variable.

Syntax:

const [data, setData] = useState(curr_State)

Explanation:

State: It represents the current state.

setState: It’s used for updating the state.

currentState: It represents the current value of the state.

Example

Code:

import React, { useState } from "react";

function ShowHideText() {

  const [isVisible, setIsVisible] = useState(false);

  return (

    <div>

      <h2>Click the button to toggle text</h2>

      <button onClick={() => setIsVisible(!isVisible)}>

        {isVisible ? "Hide" : "Show"} Text

      </button>

      {isVisible && <p>This is the text that can be shown or hidden!</p>}

    </div>

  );

}

export default ShowHideText;

Output:

Rules of useState Hook:

Here are some of the rules, which are as follows:

·        Hooks are only used with functional components.

·        useState hooks are work as asynchronous callbacks.

·        This can be called at the first level of components.

How does useState Work?

The React useState hook allows you to update and track the state of your application.

Initialization:

Firstly, you use the useState to initialize a state variable.

Syntax:

const [stateData, setStateData] = useState(initialValue);

Modify the State:

You can update the value with the use of a setter function. If the setter function is called, this automatically re-renders the component with the modified state.

Syntax:

setCount(count - 1); // Decrements the value

Example

Code:

import React, { useState } from 'react';

function Counter() {

  const [count, setCount] = useState(0);

  const increment = () => {

    setCount(count + 1);

  };

  const decrement = () => {

    setCount(count - 1);

  };

  return (

    <div>

      <h1>Count: {count}</h1>

      <button onClick={increment}>Increment</button>

      <button onClick={decrement}>Decrement</button>

    </div>

  );

}

export default Counter;

Output:


Practical Examples of useState Hook

1) Arrays in useState:

Example

Code:

import React, { useState } from "react";

function TodoList() {

  const [todos, setTodos] = useState([]);

 

  const addTodo = () => {

    const newTodo = `Task ${todos.length + 1}`;

    setTodos([...todos, newTodo]);

  };

  return (

    <div style={{ textAlign: "center" }}>

      <h2>My Todo List</h2>

      <button onClick={addTodo}>Add Task</button>

      <ul>

        {todos.map((todo, index) => (

          <li key={index}>{todo}</li>

        ))}

      </ul>

    </div>

  );

}

export default TodoList;

Output:







Objects in useState:

You cannot directly update the objects using the useState.

Example

Code:

import React, { useState } from "react";

function Product() {

  const [product, setProduct] = useState({

    name: "Wireless Headphones",

    price: 2999,

    inStock: true,

  });

  const toggleStock = () => {

    setProduct({

      ...product,

      inStock: !product.inStock,

    });

  };

  const applyDiscount = () => {

    setProduct({

      ...product,

      price: product.price - 500,

    });

  };

  return (

    <div>

      <h2>Product Details</h2>

      <p>Name: {product.name}</p>

      <p>Price: ₹{product.price}</p>

      <p>

        Availability: {product.inStock ? "In Stock" : "Out of Stock"}

      </p>

 

      <button onClick={toggleStock}>Toggle Stock</button>

      <button onClick={applyDiscount}>Apply ₹500 Discount</button>

    </div>

  );

}

export default Product;

Output:

Handling the form input:

This can be helpful for managing the form input fields as a dynamically.

Example

Code:

import React, { useState } from "react";

function Form() {

  const [formData, setFormData] = useState({

    name: "",

    email: "",

    city: "",

  });

  const handleChange = (event) => {

    const { name, value } = event.target;

    setFormData({

      ...formData,  

      [name]: value,

    });

  };

   const handleSubmit = (event) => {

    event.preventDefault();

    alert(`Name: ${formData.name}\nEmail: ${formData.email}\nCity: ${formData.city}`);

  };

  return (

    <form onSubmit={handleSubmit}>

      <h2>User Form</h2>

 

      <label>

        Name:

        <input

          type="text"

          name="name"

          value={formData.name}

          onChange={handleChange}

        />

      </label>

      <br /><br />

      <label>

        Email:

        <input

          type="email"

          name="email"

          value={formData.email}

          onChange={handleChange}

        />

      </label>

      <br /><br />

      <label>

        City:

        <input

          type="text"

          name="city"

          value={formData.city}

          onChange={handleChange}

        />

      </label>

      <br /><br />

      <button type="submit">Submit</button>

    </form>

  );

}

export default Form;

Output:

Manage the multiple useState Hooks:

You can handle one or more useState hooks in a single component to manage the different states independently.

Example

Code:

import React, { useState } from "react";

function MultiState() {

  const [name, setName] = useState("Tpoint tech");

  const [age, setAge] = useState(23);

  const [country, setCountry] = useState("India");

  return (

    <div>

      <h3>{name} - {age} years old from {country}</h3>

      <button onClick={() => setAge(age + 1)}>Increase Age</button>

    </div>

  );

}

export default MultiState;

Output:

Conditional Rendering with useState:

The useState is used for performing to apply the condition re-rendering in a functional component. Apply the condition like conditional operators, ternary operators, logical operators, etc.

Example

Code:

import React, { useState } from "react";

function Conditional() {

  const [isLoggedIn, setIsLoggedIn] = useState(false);

   const handleLogin = () => {

    setIsLoggedIn(true);

  };

  const handleLogout = () => {

    setIsLoggedIn(false);

  };

  return (

    <div>

      <h2>Conditional Rendering Example</h2>

      {isLoggedIn ? (

        <div>

          <h3>Welcome, Tpoint tech!</h3>

          <button onClick={handleLogout}>Logout</button>

        </div>

      ) : (

        <div>

          <h3>Please log in to continue</h3>

          <button onClick={handleLogin}>Login</button>

        </div>

      )}

    </div>

  );

}

export default Conditional;

Output:


Advantages of the useState Hook

Here are some of the advantages that are mentioned below:

  • ·        Code modularity and reusability
  • ·        Improved performance and efficiency
  • ·        Handle state Management
  • ·        Enhanced component interactivity

Conclusion:

This article gives you to clear understanding of React useState Hook explained with examples from beginner to professional level of developers. It allows functional components to collect, read, and modify data dynamically without the use of a class component.

For a detailed and clear understanding of ReactJS, Tpoint Tech provides React tutorials, all related concepts, and interview questions as well. 





Comments

Popular posts from this blog

Google Colab Python: A Beginner’s Guide to Coding in the Cloud

Java Tutorial: Key Concepts You Need to Know to Start Coding

Object-Oriented Programming (OOP) in python: A Complete Guide